package com.meida.common.service.impl;


import com.meida.common.service.WechatService;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @author Administrator
 */
@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private WechatUtil wechatUtil;
    private static String TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
    private static String appId = "wx649cca29fa812211";
    private static String appsecret = "a924af91eb691ab346256dd26f940cfe";

    @Override
    public Map initJSSDKConfig(String url) {
        Map<String, String> map = new HashMap<String, String>();
        try {

            //2 获取AccessToken
            String accessToken = wechatUtil.getJSSDKAccessToken(TOKENURL, appId, appsecret);
            //3 获取JssdkGetticket
            String jsapiTicket = wechatUtil.getJssdkGetticket(ticketUrl, accessToken);
            //4 签名
            String timestamp = Long.toString(System.currentTimeMillis() / 1000);
            String nonceStr = UUID.randomUUID().toString();
            String signature = WechatUtil.buildJSSDKSignature(jsapiTicket, timestamp, nonceStr, url);

            //5 返回
            map.put("url", url);
            map.put("jsapi_ticket", jsapiTicket);
            map.put("nonceStr", nonceStr);
            map.put("timestamp", timestamp);
            map.put("signature", signature);
            map.put("appid", appId);
        } catch (Exception e) {
            e.printStackTrace();
            ApiAssert.failure("初始化失败");
        }
        return map;
    }

}